package ui;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.TitledBorder;

import util.ImagePanel;
import util.JCalendar;
import util.PdfFilePrint;
import controller.CustomerController;
import controller.ServiceController;
import model.Customer;
import model.Service;
import net.miginfocom.swing.MigLayout;

public class RequestsUI implements ActionListener
{
	private boolean startup = false;

	private static RequestsUI instance = null;

	private ServiceController svCtrl;
	private CustomerController cusCtrl;
	private JFrame frameRequestsUI;

	private JTabbedPane tabbedPane;

	private ImagePanel newReqs;
	private ImagePanel allReqs;

	private Image image = null;

	private JLabel reqs;
	private JLabel reqs_1;
	private JLabel reqDrawNo;
	private JLabel reqQuantity;
	private JLabel reqDescr;
	private JLabel reqCus;
	private JLabel dimensionLabel;

	private JLabel searchBy;
	private JLabel searchWith;

	private JCalendar cal;

	private JTable allReqsTable;

	private DefaultTableModel allReqsTableModel;

	private JScrollPane allReqsTableScroll;

	private JComboBox<String> allReqsSearch;
	private JComboBox<String> newReqsCustomerSelection;

	private JButton createReq;
	private JButton emptySearchList;
	private JButton editReq;
	private JButton statistics;
	private JButton descriptionBut;
	private JButton changeStatus;
	private JButton offerMaker;

	private JTextField reqSearch;

	private JTextField reqsField;
	private JTextField reqDrawNoField;
	private JTextField reqQuantityField;
	private JTextField dimensionText;

	private JCheckBox active;

	private ArrayList<Service> reqList;
	private ArrayList<Customer> cusList;
	private JPanel panel_1;
	private JTextPane reqDescrField;
	private JScrollPane scrollPane;

	private backButton back;
	private JButton btnBack;
	private JButton btnPrint;

	public void display()
	{
		frameRequestsUI.setSize(800, 400);
		frameRequestsUI.setVisible(true);
		frameRequestsUI.setResizable(false);
		frameRequestsUI.setLocationRelativeTo(null);
	}

	public RequestsUI()
	{
		frameRequestsUI = new MainWindow();

		back = new backButton();
		back.setNumber("12");

		reqs = new JLabel("REQUESTS");
		reqs.setBounds(9, 1, 116, 28);
		reqs.setForeground(Color.white);
		reqs.setFont(new Font("Dialog", Font.BOLD, 20));

		frameRequestsUI.getContentPane().add(reqs);

		statistics = new JButton();
		statistics.setLocation(690, 326);
		statistics.setSize(100, 20);
		statistics.setOpaque(false);
		statistics.setText("Statistics");
		statistics.addActionListener(this);

		frameRequestsUI.getContentPane().add(statistics);

		try
		{
			image = ImageIO.read(new File("img/background/background.jpg"));
		}
		catch(Exception e)
		{
			msgError(null, "Could not load background");
		}

		tabbedPane = new JTabbedPane();
		tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
		tabbedPane.setBounds(0, 31, 800, 289);

		frameRequestsUI.getContentPane().add(tabbedPane);

		// all Requests panel

		allReqs = new ImagePanel(image);
		allReqs.setBounds(0,31,694, 289);

		emptySearchList = new JButton();
		emptySearchList.setText("Clear Search");
		emptySearchList.setOpaque(false);
		emptySearchList.addActionListener(this);

		descriptionBut = new JButton();
		descriptionBut.setText("Get Description");
		descriptionBut.setOpaque(false);
		descriptionBut.addActionListener(this);

		editReq = new JButton();
		editReq.setText("Edit Request");
		editReq.setOpaque(false);
		editReq.addActionListener(this);

		offerMaker = new JButton();
		offerMaker.setText("Make Offer");
		offerMaker.setOpaque(false);
		offerMaker.addActionListener(this);

		changeStatus = new JButton();
		changeStatus.setText("Change Status");
		changeStatus.setOpaque(false);
		changeStatus.addActionListener(this);

		reqSearch = new JTextField();
		reqSearch.getDocument().addDocumentListener(
				new DocumentListener()
				{

					@Override
					public void changedUpdate(DocumentEvent arg0)
					{
						searchReqs();

					}

					@Override
					public void insertUpdate(DocumentEvent arg0)
					{
						searchReqs();

					}

					@Override
					public void removeUpdate(DocumentEvent arg0)
					{
						searchReqs();

					}

				}
				);

		searchBy = new JLabel("Search for:");

		searchWith = new JLabel("Search with:");

		allReqsSearch = new JComboBox<String>();
		allReqsSearch.addActionListener(this);
		allReqsSearch.addItem("Everything");
		allReqsSearch.addItem("Name");
		allReqsSearch.addItem("Drawing Number");
		allReqsSearch.addItem("Quantity");
		allReqsSearch.addItem("Deadline");
		allReqsSearch.addItem("Customer");
		allReqsSearch.addItem("Country");
		allReqsSearch.addItem("City");

		active = new JCheckBox("Active");
		active.setOpaque(false);
		active.addActionListener(this);

		svCtrl = new ServiceController();
		cusCtrl = new CustomerController();

		String allReqsColumns[] = { "#", "Name" , "Drawing Number", "Dimension", "Quantity", "Deadline", "Customer", "City", "Country", " "};

		allReqsTableModel = new DefaultTableModel(null, allReqsColumns);

		allReqsTable = new JTable(allReqsTableModel)
		{
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int rowIndex, int colIndex)
			{
				return false;
			}

			public Class<?> getColumnClass(int column)   
			{   
				return getValueAt(0, column).getClass();   
			}  
		};

		Dimension d = allReqsTable.getPreferredSize();
		double width = d.width / allReqsColumns.length;
		double [] width_2 = {0.1, 1.0, 1.3, 1.2, 0.4, 0.5, 0.6, 0.6, 0.9, 0.2};

		for (int i = 0; i < allReqsColumns.length; i++)
			allReqsTable.getColumnModel().getColumn(i).setPreferredWidth((int) (width*width_2[i]));

		allReqsTable.setAutoCreateRowSorter(true);

		allReqsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		allReqsTableScroll = new JScrollPane(allReqsTable);

		tabbedPane.add(allReqs, "All Requests");
		GroupLayout gl_allReqs = new GroupLayout(allReqs);
		gl_allReqs.setHorizontalGroup(
				gl_allReqs.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_allReqs.createSequentialGroup()
						.addGap(10)
						.addGroup(gl_allReqs.createParallelGroup(Alignment.LEADING)
								.addComponent(allReqsTableScroll, GroupLayout.PREFERRED_SIZE, 771, GroupLayout.PREFERRED_SIZE)
								.addGroup(gl_allReqs.createSequentialGroup()
										.addGroup(gl_allReqs.createParallelGroup(Alignment.LEADING)
												.addGroup(gl_allReqs.createSequentialGroup()
														.addComponent(searchWith)
														.addGap(4)
														.addComponent(allReqsSearch, GroupLayout.PREFERRED_SIZE, 126, GroupLayout.PREFERRED_SIZE)
														.addGap(6)
														.addComponent(active))
														.addGroup(gl_allReqs.createSequentialGroup()
																.addComponent(searchBy)
																.addGap(10)
																.addComponent(reqSearch, GroupLayout.PREFERRED_SIZE, 126, GroupLayout.PREFERRED_SIZE)
																.addGap(6)
																.addComponent(emptySearchList, GroupLayout.PREFERRED_SIZE, 111, GroupLayout.PREFERRED_SIZE)))
																.addPreferredGap(ComponentPlacement.RELATED, 232, Short.MAX_VALUE)
																.addGroup(gl_allReqs.createParallelGroup(Alignment.LEADING)
																		.addGroup(gl_allReqs.createSequentialGroup()
																				.addComponent(offerMaker, GroupLayout.PREFERRED_SIZE, 111, GroupLayout.PREFERRED_SIZE)
																				.addGap(10)
																				.addComponent(changeStatus, GroupLayout.PREFERRED_SIZE, 111, GroupLayout.PREFERRED_SIZE))
																				.addGroup(gl_allReqs.createSequentialGroup()
																						.addComponent(descriptionBut, GroupLayout.PREFERRED_SIZE, 111, GroupLayout.PREFERRED_SIZE)
																						.addGap(10)
																						.addComponent(editReq, GroupLayout.PREFERRED_SIZE, 111, GroupLayout.PREFERRED_SIZE)))))
																						.addContainerGap(14, Short.MAX_VALUE))
				);
		gl_allReqs.setVerticalGroup(
				gl_allReqs.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_allReqs.createSequentialGroup()
						.addGroup(gl_allReqs.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_allReqs.createSequentialGroup()
										.addGap(11)
										.addGroup(gl_allReqs.createParallelGroup(Alignment.LEADING)
												.addGroup(gl_allReqs.createSequentialGroup()
														.addGap(4)
														.addComponent(searchWith))
														.addGroup(gl_allReqs.createSequentialGroup()
																.addGap(1)
																.addComponent(allReqsSearch, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
																.addComponent(active))
																.addGap(6)
																.addGroup(gl_allReqs.createParallelGroup(Alignment.LEADING)
																		.addGroup(gl_allReqs.createSequentialGroup()
																				.addGap(4)
																				.addComponent(searchBy))
																				.addGroup(gl_allReqs.createSequentialGroup()
																						.addGap(1)
																						.addComponent(reqSearch, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
																						.addComponent(emptySearchList)))
																						.addGroup(gl_allReqs.createSequentialGroup()
																								.addContainerGap()
																								.addGroup(gl_allReqs.createParallelGroup(Alignment.LEADING)
																										.addComponent(offerMaker)
																										.addComponent(changeStatus))
																										.addGap(6)
																										.addGroup(gl_allReqs.createParallelGroup(Alignment.LEADING)
																												.addComponent(descriptionBut)
																												.addComponent(editReq))))
																												.addPreferredGap(ComponentPlacement.RELATED)
																												.addComponent(allReqsTableScroll, GroupLayout.PREFERRED_SIZE, 184, GroupLayout.PREFERRED_SIZE)
																												.addGap(8))
				);
		allReqs.setLayout(gl_allReqs);

		// new Req panel

		newReqs = new ImagePanel(image);
		newReqs.setBounds(0,31,694, 289);

		reqs_1 = new JLabel("Name:");
		reqDrawNo = new JLabel("Drawing Number:");
		reqQuantity = new JLabel("Quantity:");
		reqDescr = new JLabel("Description:");
		reqCus = new JLabel("Customer:");

		cal = new JCalendar();
		cal.setBorder(new TitledBorder(null, "Deadline", TitledBorder.LEADING, TitledBorder.BELOW_TOP, null, null));

		reqsField = new JTextField();
		reqDrawNoField = new JTextField();
		reqQuantityField = new JTextField();

		try
		{
			cusList = cusCtrl.getAllCustomers();
		}
		catch (SQLException e1)
		{
			e1.printStackTrace();
		}

		newReqsCustomerSelection = new JComboBox<String>();
		newReqsCustomerSelection.addActionListener(this);

		createReq = new JButton();
		createReq.setText("Create Request");
		createReq.setOpaque(false);
		createReq.addActionListener(this);

		tabbedPane.add(newReqs, "New Requests");

		dimensionText = new JTextField();
		dimensionText.setColumns(10);

		dimensionLabel = new JLabel("Dimension:");

		panel_1 = new JPanel();
		panel_1.setOpaque(false);

		GroupLayout gl_newReqs = new GroupLayout(newReqs);
		gl_newReqs.setHorizontalGroup(
				gl_newReqs.createParallelGroup(Alignment.TRAILING)
				.addGroup(Alignment.LEADING, gl_newReqs.createSequentialGroup()
						.addGap(107)
						.addGroup(gl_newReqs.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_newReqs.createSequentialGroup()
										.addGroup(gl_newReqs.createParallelGroup(Alignment.LEADING)
												.addComponent(reqs_1)
												.addComponent(reqDrawNo)
												.addComponent(reqQuantity)
												.addComponent(reqDescr)
												.addGroup(gl_newReqs.createSequentialGroup()
														.addGap(1)
														.addComponent(dimensionLabel, GroupLayout.PREFERRED_SIZE, 57, GroupLayout.PREFERRED_SIZE)))
														.addGroup(gl_newReqs.createParallelGroup(Alignment.LEADING)
																.addGroup(gl_newReqs.createSequentialGroup()
																		.addGap(16)
																		.addGroup(gl_newReqs.createParallelGroup(Alignment.LEADING)
																				.addComponent(reqsField, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE)
																				.addComponent(reqDrawNoField, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE)
																				.addComponent(reqQuantityField, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE)
																				.addComponent(dimensionText, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE)))
																				.addGroup(gl_newReqs.createSequentialGroup()
																						.addGap(8)
																						.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 262, GroupLayout.PREFERRED_SIZE)))
																						.addPreferredGap(ComponentPlacement.RELATED)
																						.addComponent(cal, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
																						.addGroup(gl_newReqs.createSequentialGroup()
																								.addComponent(reqCus)
																								.addGap(49)
																								.addComponent(newReqsCustomerSelection, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE)
																								.addGap(65)
																								.addComponent(createReq)))
																								.addContainerGap(119, Short.MAX_VALUE))
				);
		gl_newReqs.setVerticalGroup(
				gl_newReqs.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_newReqs.createSequentialGroup()
						.addContainerGap(13, Short.MAX_VALUE)
						.addGroup(gl_newReqs.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_newReqs.createSequentialGroup()
										.addGap(4)
										.addComponent(reqs_1)
										.addGap(11)
										.addComponent(reqDrawNo)
										.addGap(15)
										.addComponent(reqQuantity)
										.addGap(17)
										.addComponent(reqDescr)
										.addGap(71)
										.addComponent(dimensionLabel))
										.addGroup(gl_newReqs.createSequentialGroup()
												.addGap(1)
												.addComponent(reqsField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
												.addGap(6)
												.addComponent(reqDrawNoField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
												.addGap(8)
												.addComponent(reqQuantityField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
												.addPreferredGap(ComponentPlacement.RELATED)
												.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 82, GroupLayout.PREFERRED_SIZE)
												.addGap(8)
												.addComponent(dimensionText, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
												.addComponent(cal, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
												.addGap(11)
												.addGroup(gl_newReqs.createParallelGroup(Alignment.LEADING)
														.addGroup(gl_newReqs.createSequentialGroup()
																.addGap(3)
																.addComponent(reqCus))
																.addGroup(gl_newReqs.createParallelGroup(Alignment.BASELINE)
																		.addComponent(newReqsCustomerSelection, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
																		.addComponent(createReq)))
																		.addGap(26))
				);
		panel_1.setLayout(new MigLayout("", "[grow]", "[grow]"));

		scrollPane = new JScrollPane();
		panel_1.add(scrollPane, "cell 0 0,grow");

		reqDescrField = new JTextPane();
		scrollPane.setViewportView(reqDescrField);
		newReqs.setLayout(gl_newReqs);

		try
		{
			updateReqList();
			updateCus(newReqsCustomerSelection);

			btnBack = new JButton("Back");
			btnBack.addActionListener(this);
			btnBack.setOpaque(false);
			btnBack.setBounds(9, 326, 100, 20);

			frameRequestsUI.getContentPane().add(btnBack);

			btnPrint = new JButton();
			btnPrint.addActionListener(this);
			btnPrint.setText("Print");
			btnPrint.setOpaque(false);
			btnPrint.setBounds(580, 325, 100, 20);
			frameRequestsUI.getContentPane().add(btnPrint);
		}
		catch(Exception e)
		{
			msgError(null, "Could not load information");
		}
	}

	private void updateReqList()
	{
		try
		{
			reqList = svCtrl.searchServicesByAllInfo(false, active.isSelected(), "");
			allRequestsUpdateTable(reqList);
		}
		catch(Exception e)
		{
			msgError(allReqs, "Could not load requests");
		}
	}

	public void updateCus(JComboBox<String> comboBox)
	{
		comboBox.removeAllItems();

		ArrayList<Customer> customerList = cusList;

		for(Customer cus : customerList)
			comboBox.addItem(cus.getUsername());
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		frameRequestsUI.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

		if(e.getSource() == createReq)
		{
			addReq();
		}
		else if(e.getSource() == emptySearchList)
		{
			allReqsSearch.setSelectedIndex(0);
			reqSearch.setText(null);
		}
		else if(e.getSource() == editReq)
		{
			showEditRequestDialog();
		}
		else if(e.getSource() == statistics)
		{
			StatisticsUI stats = StatisticsUI.getInstance();
			stats.display();
			frameRequestsUI.setVisible(false);
		}
		else if(e.getSource() == allReqsSearch)
		{
			if(startup)
				searchReqs();
		}
		else if(e.getSource() == descriptionBut)
		{
			getDescription();
		}
		else if(e.getSource() == changeStatus)
		{
			changeStatus();
		}
		else if(e.getSource() == active)
		{
			searchReqs();
		}
		else if(e.getSource() == offerMaker)
		{
			makeOffer();
		}
		else if(e.getSource() == btnBack)
		{
			back.goBack(back.getNumber());
		}
		else if(e.getSource() == btnPrint)
		{
			printRequestPDF();
		}

		frameRequestsUI.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
	}

	private void printRequestPDF()
	{
		if (allReqsTable.getRowCount() > 0)
		{
			ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();

			String columns[] = { "#", "Name" , "Drawing Number", "Dimension", "Quantity", "Deadline", "Customer", "City", "Country" };

			ArrayList<String> offerID = new ArrayList<String>();
			ArrayList<String> offerName = new ArrayList<String>();
			ArrayList<String> offerDrawingNo = new ArrayList<String>();
			ArrayList<String> offerDimension = new ArrayList<String>();
			ArrayList<String> offerQuantity = new ArrayList<String>();
			ArrayList<String> offerDeadline = new ArrayList<String>();
			ArrayList<String> offerCustomer = new ArrayList<String>();
			ArrayList<String> offerCity = new ArrayList<String>();
			ArrayList<String> offerCountry = new ArrayList<String>();

			list.add(offerID);
			list.add(offerName);
			list.add(offerDrawingNo);
			list.add(offerDimension);
			list.add(offerQuantity);
			list.add(offerDeadline);
			list.add(offerCustomer);
			list.add(offerCity);
			list.add(offerCountry);

			for(int i = 0; i < allReqsTable.getRowCount(); i++)
			{
				list.get(0).add(String.valueOf(allReqsTable.getValueAt(i, 0)));
				list.get(1).add(String.valueOf(allReqsTable.getValueAt(i, 1)));
				list.get(2).add(String.valueOf(allReqsTable.getValueAt(i, 2)));
				list.get(3).add(String.valueOf(allReqsTable.getValueAt(i, 3)));
				list.get(4).add(String.valueOf(allReqsTable.getValueAt(i, 4)));
				list.get(5).add(String.valueOf(allReqsTable.getValueAt(i, 5)));
				list.get(6).add(String.valueOf(allReqsTable.getValueAt(i, 6)));
				list.get(7).add(String.valueOf(allReqsTable.getValueAt(i, 7)));
				list.get(8).add(String.valueOf(allReqsTable.getValueAt(i, 8)));
			}

			PdfFilePrint pdfPrint = new PdfFilePrint();
			boolean successPDF = pdfPrint.PDFPrint("Requests", "Current Requests", "request", "Nikola", columns, list);

			if(successPDF)
				msgSuccess(null, "PDF was created successfully");
			else
				msgError(null, "There was an error creating the PDF");
		}
		else
		{
			msgError(null, "Nothing to print");
		}
	}

	private boolean checkInfoName(JTextField textField)
	{

		if((textField.getText().trim().length() == 0) || (textField.getText().trim().length() > 32))
			return false;

		return true;
	}
	private boolean checkInfoGeneral(JTextField textField)
	{

		if((textField.getText().trim().length() == 0) && textField.getText().matches("\\d*"))
			return false;

		return true;
	}

	private boolean checkInfoDimensions(JTextField textField)
	{

		if((textField.getText().trim().length() == 0) || (textField.getText().trim().length() > 52))
			return false;

		return true;
	}

	private void addReq()
	{
		boolean checkName = checkInfoName(reqsField);
		boolean checkDimension = checkInfoDimensions(dimensionText);
		boolean checkQuantity = checkInfoGeneral(reqQuantityField);
		boolean checkDrawing = checkInfoGeneral(reqDrawNoField);

		if(checkName && checkDimension && checkQuantity && checkDrawing)
		{
			try
			{
				Customer cusObj = new Customer();

				try
				{
					cusObj = cusCtrl.searchCustomerByName(newReqsCustomerSelection.getSelectedItem().toString());
				} 
				catch (SQLException e)
				{
					msgError(newReqs, "Could not load customer information");
					e.printStackTrace();
				}

				int good = svCtrl.addNewService(0,false,reqsField.getText().trim(), Integer.parseInt(reqDrawNoField.getText().trim()), 0 ,dimensionText.getText().trim() ,Integer.parseInt(reqQuantityField.getText().trim()), reqDescrField.getText(), cal.getPeriod(), cusObj);

				if(good > 0)
				{
					msgSuccess(newReqs, "Request \"" + reqsField.getText().trim() + "\" has been added successfully");

					reqsField.setText(null);
					reqDrawNoField.setText(null);
					reqQuantityField.setText(null);
					reqDescrField.setText(null);
					dimensionText.setText(null);

					searchReqs();
				}
				else if(good < 0)
				{
					msgError(newReqs, "There was an error adding the request.\n");
				}
			}

			catch(Exception ex)
			{
				msgError(newReqs, "There was an error adding the request.");
			}
		} 
		else
		{
			msgError(newReqs, "You cannot proceed due to errors in your input. \n Please check and try again");
		}
	}

	private void showEditRequestDialog()
	{
		if(allReqsTable.getSelectedRow() > -1)
		{
			int reqID = Integer.valueOf(String.valueOf(allReqsTable.getValueAt(allReqsTable.getSelectedRow(), 0)));

			Service req = new Service();

			try
			{
				req = svCtrl.getOne(reqID);
			} 
			catch(SQLException e)
			{
				msgError(newReqs, "Cannot retrieve needed information");
				e.printStackTrace();
			}

			JPanel paneled = new JPanel();

			JTextField editReqName = new JTextField(req.getName());
			JTextField editReqDrawNo = new JTextField(String.valueOf(req.getDrawingNo()));
			JTextField editReqQuantity = new JTextField(String.valueOf(req.getProdQuantity()));
			JTextField editReqDimension = new JTextField(req.getDimensions());
			JTextPane editReqDescription = new JTextPane();
			editReqDescription.setText(req.getDescription());

			JScrollPane scrollPane_descri = new JScrollPane(editReqDescription);
			scrollPane_descri.setViewportView(editReqDescription);
			scrollPane_descri.setPreferredSize(new Dimension(50, 50));
			scrollPane_descri.setLocation(0, 0);

			JCalendar editCal = new JCalendar();
			editCal.setBorder(new TitledBorder(null, "Deadline:", TitledBorder.LEADING, TitledBorder.BELOW_TOP, null, null));
			JComboBox <String> editCustomer = newReqsCustomerSelection;

			updateCus(editCustomer);

			JLabel lblName = new JLabel("Name:");
			JLabel lblDrawingNumber = new JLabel("Drawing Number:");
			JLabel lblQuantity = new JLabel("Quantity:");
			JLabel lblDimension = new JLabel("Dimension:");
			JLabel lblDescription = new JLabel("Description:");
			JLabel lblCustomer = new JLabel("Customer:");

			GroupLayout panel = new GroupLayout(paneled);
			panel.setHorizontalGroup(
					panel.createParallelGroup(Alignment.LEADING)
					.addGroup(panel.createSequentialGroup()
							.addGap(10)
							.addGroup(panel.createParallelGroup(Alignment.LEADING)
									.addComponent(lblName)
									.addComponent(lblDrawingNumber)
									.addComponent(lblQuantity)
									.addComponent(lblDimension)
									.addComponent(lblDescription)
									.addComponent(lblCustomer))
									.addGap(20)
									.addGroup(panel.createParallelGroup(Alignment.LEADING)
											.addGroup(panel.createSequentialGroup()
													.addPreferredGap(ComponentPlacement.RELATED)
													.addGroup(panel.createParallelGroup(Alignment.LEADING)
															.addComponent(scrollPane_descri, 250, 250,250)
															.addComponent(editCustomer, 0, 125, Short.MAX_VALUE)
															.addComponent(editReqDimension, GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)))
															.addComponent(editReqQuantity, 150, 150, 150)
															.addGroup(panel.createParallelGroup(Alignment.LEADING, false)
																	.addComponent(editReqDrawNo)
																	.addComponent(editReqName, GroupLayout.PREFERRED_SIZE, 150, GroupLayout.PREFERRED_SIZE)))
																	.addGap(18)
																	.addComponent(editCal, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
																	.addGap(10))
					);
			panel.setVerticalGroup(
					panel.createParallelGroup(Alignment.LEADING)
					.addGroup(panel.createSequentialGroup()
							.addGroup(panel.createParallelGroup(Alignment.LEADING)
									.addGroup(panel.createSequentialGroup()
											.addGap(15)
											.addGroup(panel.createParallelGroup(Alignment.BASELINE)
													.addComponent(lblName)
													.addComponent(editReqName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
													.addPreferredGap(ComponentPlacement.RELATED)
													.addGroup(panel.createParallelGroup(Alignment.BASELINE)
															.addComponent(lblDrawingNumber)
															.addComponent(editReqDrawNo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
															.addPreferredGap(ComponentPlacement.RELATED)
															.addGroup(panel.createParallelGroup(Alignment.BASELINE)
																	.addComponent(lblQuantity)
																	.addComponent(editReqQuantity, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
																	.addPreferredGap(ComponentPlacement.RELATED)
																	.addGroup(panel.createParallelGroup(Alignment.BASELINE)
																			.addComponent(lblDimension)
																			.addComponent(editReqDimension, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
																			.addPreferredGap(ComponentPlacement.RELATED)
																			.addGroup(panel.createParallelGroup(Alignment.BASELINE)
																					.addComponent(lblDescription)
																					.addComponent(scrollPane_descri, 125,125,125))
																					.addPreferredGap(ComponentPlacement.RELATED)
																					.addGroup(panel.createParallelGroup(Alignment.BASELINE)
																							.addComponent(lblCustomer)
																							.addComponent(editCustomer, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
																							.addGroup(panel.createSequentialGroup()
																									.addContainerGap()
																									.addComponent(editCal, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
																									.addContainerGap(15, Short.MAX_VALUE))
					);
			paneled.setLayout(panel);

			int option = JOptionPane.showConfirmDialog(allReqs, paneled,"Edit request", JOptionPane.OK_CANCEL_OPTION);

			if(option == JOptionPane.YES_OPTION)
			{
				boolean checkName = checkInfoName(editReqName);
				boolean checkDimension = checkInfoDimensions(editReqDimension);
				boolean checkQuantity = checkInfoGeneral(editReqQuantity);
				boolean checkDrawing = checkInfoGeneral(editReqDrawNo);

				if(checkName && checkDimension && checkQuantity && checkDrawing)
				{
					Customer cusObj = new Customer();

					try
					{
						cusObj = cusCtrl.searchCustomerByName(editCustomer.getSelectedItem().toString().trim());
					}
					catch(Exception e)
					{
						msgError(allReqs, "Cannot retrieve needed information");
					}
					int success = -1;

					try
					{
						success = svCtrl.updateService(false,reqID,editReqName.getText(),0,editReqDimension.getText(), Integer.parseInt(editReqDrawNo.getText().trim()), Integer.parseInt(editReqQuantity.getText().trim()), editReqDescription.getText(), editCal.getPeriod(), cusObj);

					}
					catch (SQLException e)
					{
						msgError(allReqs, "There was an error while editing the request");
					}

					if(success > 0)
					{
						msgSuccess(allReqs, "Request " + editReqName.getText().trim() + " has been edited successfully");

						searchReqs();
					}
					else 
					{
						msgError(allReqs, "Request  has not been edited successfully");
					}
				}
				else
				{
					msgError(allReqs, "The information you have inserted is not correct, please try again");
				}
			}
		}
		else
		{
			msgError(allReqs, "You have not selected a request");
		}
	}

	private void allRequestsUpdateTable(ArrayList<Service> reqLister)
	{
		if(reqLister.size() > 0)
		{
			tableClearList();

			for(Service req : reqLister)
			{
				allReqsTableModel.addRow(
						new Object[]
								{
								req.getServiceID(),
								req.getName(),
								req.getDrawingNo(),
								req.getDimensions(),
								req.getProdQuantity(),
								req.getDeadline(),
								req.getCustomer().getUsername(),
								req.getCustomer().getCity(),
								req.getCustomer().getCity().getCountry(),
								new ImageIcon("img/flags/" + req.getCustomer().getCity().getCountry().getTld() + ".png")
								}

						);
			}
		}
	}

	private void tableClearList()
	{
		DefaultTableModel dTM = (DefaultTableModel) allReqsTable.getModel();

		while(dTM.getRowCount() > 0)
			dTM.removeRow(0);
	}

	private void searchReqs()
	{

		String clause = allReqsSearch.getSelectedItem().toString().toLowerCase();
		String search = reqSearch.getText();

		try
		{
			tableClearList();

			switch(clause)
			{
				case "everything" : reqList = svCtrl.searchServicesByAllInfo(false,active.isSelected(), search); break;
				case "name" : reqList = svCtrl.searchServicesByName(search, active.isSelected(), false); break;
				case "quantity" : reqList = svCtrl.searchServicesByProdQuantity(Integer.parseInt(search), active.isSelected(), false); break;
				case "drawing number" : reqList = svCtrl.searchServicesByDrawingNo(Integer.parseInt(search), active.isSelected(),false); break;
				case "dimensions" : reqList = svCtrl.searchServicesByDimension(search, active.isSelected(), false); break;
				case "customer" : reqList = svCtrl.searchServicesByCustomer(search, active.isSelected(), false); break;
				case "deadline" : reqList = svCtrl.searchServicesByDeadline(search, active.isSelected(), false); break;
				case "country" : reqList = svCtrl.searchServicesByCountry(search, active.isSelected(), false); break;
				case "country tld" : reqList = svCtrl.searchServicesByCountryTld(search, active.isSelected(), false); break;
				case "city" : reqList = svCtrl.searchServicesByCity(search, active.isSelected(), false); break;
			}

			allRequestsUpdateTable(reqList);

		}
		catch(Exception e)
		{
			msgError(allReqs, "Could not load requests");
		}

		if(!startup)
			startup = true;
	}

	private void changeStatus()
	{
		if(allReqsTable.getSelectedRow() > -1)
		{
			int reqID = Integer.valueOf(String.valueOf(allReqsTable.getValueAt(allReqsTable.getSelectedRow(), 0)));

			JPanel panel = new JPanel(new GridLayout(0,2,5,5));

			JComboBox <String> reqStatus = new JComboBox<String>();
			reqStatus.addItem("Active");
			reqStatus.addItem("Unactive");

			panel.add(reqStatus);

			int option = JOptionPane.showConfirmDialog(allReqs,panel, "Change Status", JOptionPane.OK_CANCEL_OPTION);

			if(option == JOptionPane.YES_OPTION)
			{
				int success = 0;

				switch(reqStatus.getSelectedItem().toString().toLowerCase())
				{
					case "active": 
						try
						{
							success	 = svCtrl.changeStatus(1, reqID);
						} 
						catch (SQLException e)
						{
							msgError(allReqs, "Could not modify the information, please try again");
						}
						break;

					case "unactive":
						try
						{
							success = svCtrl.changeStatus(0, reqID);

						} 
						catch(SQLException e)
						{
							msgError(allReqs, "Could not modify the information, please try again");
							e.printStackTrace();
						}
				}

				if(success > 0)
				{
					msgSuccess(allReqs, "Request has been edited successfully");
					searchReqs();
				}
				else
				{
					msgError(allReqs, "There was an error while editing the request");
				}

			}
		}
		else
		{
			msgError(allReqs, "You have not selected a request");
		}
	}

	private void getDescription()
	{
		if(allReqsTable.getSelectedRow() > -1)
		{
			int reqID = Integer.valueOf(String.valueOf(allReqsTable.getValueAt(allReqsTable.getSelectedRow(), 0)));

			Service req = new Service();

			try
			{
				req = svCtrl.getOne(reqID);
			}
			catch(SQLException e)
			{
				msgError(allReqs, "Cannoted retrieve needed information");
			}


			JTextPane reqDescrField_1 = new JTextPane();
			reqDescrField_1.setText(req.getDescription());
			JScrollPane scrollPane_1 = new JScrollPane(reqDescrField_1);	
			//scrollPane_1.getViewport().add(reqDescrField_1);
			scrollPane_1.setViewportView(reqDescrField_1);
			scrollPane_1.setPreferredSize(new Dimension(150, 150));
			scrollPane_1.setLocation(0, 0);
			JOptionPane.showConfirmDialog(allReqs,scrollPane_1, "Description", JOptionPane.DEFAULT_OPTION);

		}
		else
		{
			msgError(allReqs, "You have not selected a request");
		}
	}

	private void makeOffer()
	{
		if(allReqsTable.getSelectedRow() > -1)
		{
			int reqID = Integer.valueOf(String.valueOf(allReqsTable.getValueAt(allReqsTable.getSelectedRow(), 0)));

			Service req = new Service();


			try
			{
				req = svCtrl.getOne(reqID);
			} 
			catch(SQLException e)
			{
				msgError(allReqs, "Cannot retrieve needed information");
			}

			JTextField price = new JTextField();

			JPanel panel = new JPanel();

			panel.setLayout(new GridLayout(0,2,5,5));

			panel.add(new JLabel("Price:"));
			panel.add(price);

			int option = JOptionPane.showConfirmDialog(allReqs, panel, "Make offer", JOptionPane.OK_CANCEL_OPTION);

			if(option == JOptionPane.YES_OPTION)
			{
				boolean priceCheck = checkInfoGeneral(price);
				if(priceCheck)
				{
					try
					{
						int good = svCtrl.transferServices(reqID,true,req.getName(), req.getDrawingNo(), Double.valueOf(price.getText()) ,req.getDimensions() ,req.getProdQuantity(), req.getDescription(), req.getDeadline(), req.getCustomer());

						if(good > 0)
						{
							searchReqs();

							msgSuccess(allReqs, "Request \"" + reqsField.getText().trim() + "\" has been added successfully");
						}
						else if(good < 0)
						{
							msgError(allReqs, "There was an error adding the request.\n");
						}
					}
					catch(Exception ex)
					{
						msgError(allReqs, "There was an error adding the request.");
					}
				} else
				{
					msgError(allReqs, "The price was not inserted corectly");
				}
			}
		}
		else
		{
			msgError(allReqs, "You have not selected a request");
		}
	}

	public static void main(String[] args) 
	{
		try 
		{
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 

			RequestsUI reqUI = new RequestsUI();
			reqUI.display();
		}
		catch(Exception e)
		{
			System.out.println("[ERROR] Request Menu cannot load");
			e.printStackTrace();
		}

	}

	public static RequestsUI getInstance()
	{
		if(instance == null)
			instance = new RequestsUI();

		return instance;
	}

	private void msgError(JPanel panel, String error)
	{
		JOptionPane.showConfirmDialog(panel, error, "Error", JOptionPane.PLAIN_MESSAGE, JOptionPane.ERROR_MESSAGE);
	}

	private void msgSuccess(JPanel panel, String success)
	{
		JOptionPane.showMessageDialog(panel, success, "Success", 1);
	}
}